package com.example.viewmodeldemo;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: tuyrt7 on 2020/9/3.
 */
public class TimerViewModel extends ViewModel {
    private Timer mTimer;
    private int currentSecond;
    private OnTimerChangeListener mListener;

    private MutableLiveData<Integer> current;

    public LiveData<Integer> getCurrentSecond() {
        if (current == null) {
            current = new MutableLiveData<>();
        }
        return current;
    }

    public void startTiming() {
        if (mTimer == null) {
            currentSecond = 0;
            mTimer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    currentSecond++;

                    current.postValue(currentSecond);

                    if (mListener != null) {
                        mListener.onchange(currentSecond);
                    }
                }
            };
            mTimer.schedule(task, 1000, 1000);
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        mTimer.cancel();
    }

    public void reset() {
        current.setValue(0);
        currentSecond = 0;
    }


    public void setOnTimerChangeListener(OnTimerChangeListener listener) {
        mListener = listener;
    }

    public interface OnTimerChangeListener {

        void onchange(int second);
    }

}
